<!--
Kimi PPT生成页面 - 基于营销方案生成PPT演示文稿
功能：接收营销方案数据，调用Kimi API生成PPT
-->
<template>
  <div class="kimi-page">
    <div class="container">
      <!-- 页面头部 -->
      <header class="page-header">
        <div class="header-content">
          <button @click="goBack" class="back-btn">
            <ArrowLeft class="w-4 h-4" />
            返回豆包
          </button>
          <div class="header-info">
            <h1>Kimi AI PPT生成</h1>
            <p>基于营销方案生成专业PPT演示文稿</p>
          </div>
        </div>
      </header>

      <!-- 主要内容 -->
      <main class="main-content">
        <div class="content-layout">
          <!-- 左侧面板 -->
          <aside class="sidebar">
            <!-- 方案摘要 -->
            <div class="plan-summary">
              <h3>营销方案摘要</h3>
              <div class="summary-content">
                <div class="summary-item">
                  <label>核心目标</label>
                  <span>{{ requirementData.core_goal || '未设置' }}</span>
                </div>
                <div class="summary-item">
                  <label>目标受众</label>
                  <span>{{ requirementData.target_audience || '未设置' }}</span>
                </div>
                <div class="summary-item">
                  <label>人均预算</label>
                  <span>{{ requirementData.budget_per_person || '未设置' }}</span>
                </div>
              </div>
            </div>

            <!-- 确认的方案内容 -->
            <div class="confirmed-plan" v-if="confirmedPlan">
              <h3>确认的营销方案</h3>
              <div class="plan-content">
                <div class="plan-text">{{ confirmedPlan }}</div>
              </div>
            </div>

            <!-- PPT配置 -->
            <div class="ppt-config">
              <h3>PPT配置</h3>
              <div class="config-form">
                <div class="form-group">
                  <label>主题风格</label>
                  <select v-model="pptConfig.theme" class="form-control">
                    <option value="business">商务风格</option>
                    <option value="creative">创意风格</option>
                    <option value="minimal">简约风格</option>
                    <option value="modern">现代风格</option>
                  </select>
                </div>
                <div class="form-group">
                  <label>页面数量</label>
                  <select v-model="pptConfig.pageCount" class="form-control">
                    <option value="10">10页</option>
                    <option value="15">15页</option>
                    <option value="20">20页</option>
                    <option value="25">25页</option>
                  </select>
                </div>
                <div class="form-group">
                  <label>演示风格</label>
                  <select v-model="pptConfig.style" class="form-control">
                    <option value="detailed">详细版</option>
                    <option value="summary">摘要版</option>
                    <option value="executive">高管版</option>
                  </select>
                </div>
                <div class="form-group">
                  <label>特殊要求</label>
                  <textarea 
                    v-model="pptConfig.specialRequirements" 
                    class="form-control" 
                    rows="3" 
                    placeholder="请输入特殊要求或补充说明..."
                  ></textarea>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <button @click="sendToKimi" class="send-btn" :disabled="!confirmedPlan">
                <Send class="w-4 h-4" />
                发送到Kimi
              </button>
              <button @click="refreshIframe" class="refresh-btn">
                <RefreshCw class="w-4 h-4" />
                刷新页面
              </button>
              <button @click="downloadPPT" class="download-btn" :disabled="!generatedPPT">
                <Download class="w-4 h-4" />
                下载PPT
              </button>
            </div>
          </aside>

          <!-- 右侧Kimi界面 -->
          <div class="main-panel">
            <div class="iframe-container">
              <div class="iframe-header">
                <h3>Kimi AI PPT生成器</h3>
                <div class="iframe-controls">
                  <div class="connection-status" :class="{ connected: isIframeLoaded }">
                    <div class="status-dot"></div>
                    <span>{{ isIframeLoaded ? '已连接' : '连接中...' }}</span>
                  </div>
                  <button @click="toggleFullscreen" class="fullscreen-btn" title="全屏">
                    <Maximize class="w-4 h-4" />
                  </button>
                </div>
              </div>
              <div class="iframe-wrapper">
                <iframe
                  ref="kimiIframe"
                  :src="kimiUrl"
                  class="kimi-iframe"
                  @load="onIframeLoad"
                  sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation allow-downloads"
                ></iframe>
                <div v-if="!isIframeLoaded" class="loading-overlay">
                  <div class="loading-spinner"></div>
                  <p>正在加载Kimi AI PPT生成器...</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMarketingStore } from '../stores/marketing'
import { ArrowLeft, Send, Download, RefreshCw, Maximize } from 'lucide-vue-next'
import { copyText, getClipboardCapabilities } from '../utils/clipboard'

const router = useRouter()
const marketingStore = useMarketingStore()

// 页面状态
const isLoading = ref(true)
const isIframeLoaded = ref(false)
const generatedPPT = ref(false)
const isFullscreen = ref(false)
const kimiIframe = ref(null)

// Kimi网站URL
const kimiUrl = ref('https://www.kimi.com/kimiplus/slides')

// 需求数据（从豆包页面传递过来）
const requirementData = computed(() => marketingStore.getRequirementData() || {})

// 确认的营销方案（从豆包页面传递过来）
const confirmedPlan = computed(() => marketingStore.getGeneratedPlan() || '')

// PPT配置
const pptConfig = reactive({
  theme: 'business',
  pageCount: '15',
  style: 'detailed',
  specialRequirements: ''
})

// 方法
const goBack = () => {
  router.push('/doubao')
}

const onIframeLoad = () => {
  isLoading.value = false
  isIframeLoaded.value = true
  console.log('Kimi iframe loaded successfully')
  setupIframeMessaging()
}

const setupIframeMessaging = () => {
  // 监听来自iframe的消息
  window.addEventListener('message', (event) => {
    if (event.origin !== 'https://www.kimi.com') {
      return
    }
    
    const { type, data } = event.data
    
    switch (type) {
      case 'ppt_generated':
        generatedPPT.value = true
        console.log('PPT生成完成:', data)
        showNotification('✅ PPT生成完成！', 'success')
        break
      case 'iframe_ready':
        console.log('Kimi iframe准备就绪')
        break
      default:
        console.log('收到未知消息类型:', type)
    }
  })
}

const sendToKimi = async () => {
  if (!confirmedPlan.value) {
    showNotification('⚠️ 请先在豆包页面确认营销方案', 'warning')
    return
  }

  try {
    // 构建要发送给Kimi的内容
    const kimiPrompt = buildKimiPrompt()
    
    // 尝试通过postMessage发送数据到iframe
    if (kimiIframe.value && kimiIframe.value.contentWindow) {
      kimiIframe.value.contentWindow.postMessage({
        type: 'ppt_generation_request',
        data: {
          prompt: kimiPrompt,
          config: pptConfig
        }
      }, 'https://www.kimi.com')
      
      console.log('数据已发送到Kimi iframe')
    }
    
    // 使用新的智能复制功能
    const copyResult = await copyText(kimiPrompt, {
      showFallbackDialog: true,
      fallbackTitle: 'Kimi PPT生成提示词'
    })
    
    if (copyResult.success) {
      showNotification(`✅ 提示词已发送到Kimi，同时${copyResult.message}<br><small style="opacity: 0.9;">如果自动发送失败，请在Kimi界面中粘贴使用 (Ctrl+V)</small>`, 'success')
    } else {
      // 如果复制失败，手动复制对话框已经显示，只显示简单通知
      showNotification('📤 提示词已发送到Kimi<br><small style="opacity: 0.9;">请查看弹出的复制对话框</small>', 'info')
    }
    
  } catch (error) {
    console.error('发送到Kimi失败:', error)
    showNotification('❌ 发送失败<br><small style="opacity: 0.9;">请手动复制提示词到Kimi界面</small>', 'error')
  }
}

const buildKimiPrompt = () => {
  const requirement = requirementData.value
  const plan = confirmedPlan.value
  
  return `🎯 请基于以下营销需求和确认的方案，生成一个专业的PPT演示文稿：

## 📋 营销需求信息
• 核心目标：${requirement.core_goal || '未设置'}
• 目标受众：${requirement.target_audience || '未设置'}
• 人均预算：${requirement.budget_per_person || '未设置'}
• 方案侧重点：${requirement.focus_point || '未设置'}
• 礼品类型偏好：${requirement.gift_preference || '未设置'}
• 具体产品：${requirement.specific_product || '未设置'}
• 客户偏好：${requirement.customer_preference || '未设置'}
• 客户痛点：${requirement.customer_pain_points || '未设置'}

## 📝 确认的营销方案
${plan || '暂无确认方案'}

## 🎨 PPT要求
• 主题风格：${pptConfig.theme === 'business' ? '商务风格' : pptConfig.theme === 'creative' ? '创意风格' : pptConfig.theme === 'minimal' ? '简约风格' : '现代风格'}
• 页面数量：${pptConfig.pageCount}页
• 演示风格：${pptConfig.style === 'detailed' ? '详细版' : pptConfig.style === 'summary' ? '摘要版' : '高管版'}
• 特殊要求：${pptConfig.specialRequirements || '无特殊要求'}

## 📊 PPT结构建议
1. 封面页 - 营销方案标题和基本信息
2. 目录页 - 整体结构概览
3. 背景分析 - 市场环境和客户痛点
4. 目标设定 - 核心目标和预期效果
5. 方案详情 - 具体实施策略和步骤
6. 预算分配 - 成本结构和ROI预测
7. 时间规划 - 项目时间线和里程碑
8. 风险控制 - 潜在风险和应对措施
9. 效果评估 - KPI指标和监控方法
10. 总结展望 - 方案亮点和未来规划

请生成一个结构清晰、内容丰富、视觉美观的PPT，确保每页内容充实且具有实用价值。`
}

const refreshIframe = () => {
  isLoading.value = true
  isIframeLoaded.value = false
  if (kimiIframe.value) {
    kimiIframe.value.src = kimiIframe.value.src
  }
}

const toggleFullscreen = () => {
  const iframeContainer = kimiIframe.value?.parentElement?.parentElement
  if (!iframeContainer) return
  
  if (!isFullscreen.value) {
    if (iframeContainer.requestFullscreen) {
      iframeContainer.requestFullscreen()
    } else if (iframeContainer.webkitRequestFullscreen) {
      iframeContainer.webkitRequestFullscreen()
    } else if (iframeContainer.msRequestFullscreen) {
      iframeContainer.msRequestFullscreen()
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    }
  }
}

const handleFullscreenChange = () => {
  isFullscreen.value = !!(document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement)
}

const downloadPPT = () => {
  // 由于跨域限制，无法直接控制Kimi的下载功能
  // 提供更详细的指导
  showInstruction()
}

const showNotification = (message, type = 'info') => {
  const colors = {
    success: '#4CAF50',
    error: '#f44336',
    warning: '#ff9800',
    info: '#2196F3'
  }
  
  const notification = document.createElement('div')
  notification.innerHTML = `
    <div style="position: fixed; top: 20px; right: 20px; background: ${colors[type]}; color: white; padding: 15px 20px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 10000; font-size: 14px; max-width: 300px;">
      ${message}
    </div>
  `
  document.body.appendChild(notification)
  
  setTimeout(() => {
    if (document.body.contains(notification)) {
      document.body.removeChild(notification)
    }
  }, 3001)
}

const showInstruction = () => {
  const instruction = document.createElement('div')
  instruction.innerHTML = `
    <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 30px; border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,0.2); z-index: 10000; max-width: 400px; text-align: center;">
      <h3 style="margin: 0 0 15px 0; color: #333;">📥 下载PPT指南</h3>
      <p style="margin: 0 0 20px 0; color: #666; line-height: 1.5;">由于安全限制，请按以下步骤下载PPT：</p>
      <ol style="text-align: left; color: #555; line-height: 1.6;">
        <li>在Kimi界面中找到生成的PPT</li>
        <li>点击PPT右上角的下载按钮</li>
        <li>选择合适的格式进行下载</li>
      </ol>
      <button onclick="this.parentElement.parentElement.remove()" style="background: #667eea; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; margin-top: 15px;">我知道了</button>
    </div>
  `
  document.body.appendChild(instruction)
}

const cleanup = () => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('msfullscreenchange', handleFullscreenChange)
}

// 组件挂载时的初始化
onMounted(() => {
  // 检查是否有需求数据和确认的方案
  if (!requirementData.value || Object.keys(requirementData.value).length === 0) {
    showNotification('⚠️ 缺少需求数据<br><small style="opacity: 0.9;">请先完成需求填写</small>', 'warning')
    
    setTimeout(() => {
      router.push('/')
    }, 2000)
    return
  }
  
  if (!confirmedPlan.value) {
    showNotification('⚠️ 缺少确认方案<br><small style="opacity: 0.9;">请先在豆包页面确认营销方案</small>', 'warning')
    
    setTimeout(() => {
      router.push('/doubao')
    }, 2000)
    return
  }
  
  // 监听全屏变化
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('msfullscreenchange', handleFullscreenChange)
  
  console.log('KimiPage initialized with data:', {
    requirement: requirementData.value,
    plan: confirmedPlan.value
  })
})

onUnmounted(() => {
  cleanup()
})
</script>

<style scoped>
.kimi-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  width: 100%;
}

/* 页面头部 */
.page-header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 20px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 10px 20px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.header-info h1 {
  color: white;
  font-size: 1.8rem;
  font-weight: 700;
  margin: 0 0 5px 0;
}

.header-info p {
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  font-size: 14px;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  padding: 30px 0;
}

.content-layout {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 30px;
  height: calc(100vh - 200px);
}

/* 左侧边栏 */
.sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 方案摘要面板 */
.plan-summary-panel {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.plan-summary-panel h3 {
  color: #2c3e50;
  font-size: 1.2rem;
  font-weight: 600;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #667eea;
}

.summary-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.summary-item label {
  font-size: 12px;
  font-weight: 600;
  color: #667eea;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.summary-item span {
  color: #2c3e50;
  font-size: 14px;
  line-height: 1.4;
}

/* 配置面板 */
.config-panel {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  flex: 1;
}

.config-panel h3 {
  color: #2c3e50;
  font-size: 1.2rem;
  font-weight: 600;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #4facfe;
}

.config-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 25px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.form-select,
.form-input,
.form-textarea {
  padding: 12px 16px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: white;
}

.form-select:focus,
.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #4facfe;
  box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
}

.radio-group {
  display: flex;
  gap: 15px;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #2c3e50;
}

.radio-item input[type="radio"] {
  width: 16px;
  height: 16px;
  accent-color: #4facfe;
}

.panel-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.btn-primary {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(79, 172, 254, 0.3);
}

.btn-success {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
}

.btn-success:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(17, 153, 142, 0.3);
}

.btn-success:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.btn-full {
  width: 100%;
}

/* 右侧主面板 */
.main-panel {
  display: flex;
  flex-direction: column;
}

.iframe-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.iframe-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  color: white;
}

.iframe-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 1.1rem;
  font-weight: 600;
}

.iframe-controls {
  display: flex;
  gap: 10px;
}

.control-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.iframe-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.kimi-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background: white;
}

/* 加载遮罩 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20px;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e1e8ed;
  border-top: 4px solid #4facfe;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-overlay p {
  color: #2c3e50;
  font-size: 16px;
  font-weight: 500;
  margin: 0;
}

/* 图标样式 */
.icon-arrow-left::before { content: '←'; }
.icon-presentation::before { content: '📊'; }
.icon-send::before { content: '📤'; }
.icon-download::before { content: '⬇️'; }
.icon-refresh::before { content: '🔄'; }
.icon-fullscreen::before { content: '⛶'; }

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-layout {
    grid-template-columns: 320px 1fr;
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .content-layout {
    grid-template-columns: 1fr;
    height: auto;
  }
  
  .sidebar {
    order: 2;
  }
  
  .main-panel {
    order: 1;
    height: 60vh;
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .container {
    padding: 0 15px;
  }
}
</style>